package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import cn.tedu._03vehicle.mapper.UserMapper;
import cn.tedu._03vehicle.pojo.dto.UserLoginParam;
import cn.tedu._03vehicle.pojo.dto.UserRegParam;
import cn.tedu._03vehicle.pojo.entity.User;
import cn.tedu._03vehicle.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.resource.ResourceUrlProvider;

import java.util.Date;

@Slf4j
@RestController
@Tag(name = "01-用户管理模块")
@RequestMapping("/v1/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    /**
     * 1.注册功能
     */
    @PostMapping("reg")
    @Operation(summary = "注册功能")
    @ApiOperationSupport(order = 10)
    public JsonResult reg(@RequestBody @Validated UserRegParam userRegParam){
        log.debug("注册业务,参数:" + userRegParam);
        /*
            1.接收客户端传递的数据[已完成];
            2.数据合法性的校验[暂时不做,后期使用验证框架完成];
            3.确认用户名是否被占用[SELECT查询接口];
              SELECT COUNT(*) FROM user WHERE username = ?;
              3.1 被占用:直接返回;
              3.2 未被占用:数据存入数据表[INSERT插入接口],返回成功信息;
         */
        String username = userRegParam.getUsername();
        int count = userMapper.selectByUsername(username);
        if (count > 0){//被占用
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        //未被占用
        User user = new User();
        BeanUtils.copyProperties(userRegParam, user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        log.debug("实体类:" + user);
        int i = userMapper.insertUser(user);
        if (i > 0){//注册成功
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.UNKNOWN_ERROR);
    }

    /**
     * 2.登录功能
     */
    @PostMapping("/login")
    @Operation(summary = "登录功能")
    @ApiOperationSupport(order = 20)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, HttpSession session){
        log.debug("登录业务,参数:" + userLoginParam);
        /*
            1.查询用户名和密码是否正确[SELECT查询接口];
            2.判断查询结果
              2.1 登录成功:返回JsonResult对象,包含用户信息userVO;
              2.2 登录失败:返回JsonResult对象;
         */
        //SELECT id,username FROM user WHERE username = ? AND password = ?
        UserVO userVO = userMapper.selectByUsernameAndPassword(userLoginParam);
        if (userVO == null){ //用户名或密码错误
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        //在服务器的内存中保存该用户的会话标识;
        //服务器内存: {"user": {"id":100, "username":"lucy"}}
        session.setAttribute("user", userVO);
        //登录成功
        return JsonResult.ok(userVO);
    }

    /**
     * 3.获取当前用户功能
     *   测试步骤:
     *   1.未登录情况下访问该接口,data为null;
     *   2.登录成功后,访问该接口,data不为null,可以成功获取到登录用户的信息;
     */
    @GetMapping("/currentUser")
    @Operation(summary = "获取当前用户")
    @ApiOperationSupport(order = 30)
    public JsonResult currentUser(HttpSession session){
        //服务端内存中获取会话;
        UserVO userVO = (UserVO) session.getAttribute("user");

        //情况1:用户未登录 ---> {"state":2000,"message":"操作成功","data":null}
        //情况2:用户已登录 ---> {"state":2000,"message":"操作成功","data":{"id":100,"username":"lucy"}}
        /*
            前端代码:
            前端:response.data.data: 获取userVO
            if (response.data.data == null){
                重定向到登录页面;
            }else {
                从userVO中获取username的值;
                页面中显示用户名:欢迎你,xxx
            }
         */
        return JsonResult.ok(userVO);
    }

    /**
     * 4.退出登录功能
     *   4.1 登录成功;
     *   4.2 获取当前用户[获取成功];
     *   4.3 退出登录;
     *   4.4 获取当前用户[获取失败];
     */
    @GetMapping("/logout")
    @Operation(summary = "退出登录功能")
    @ApiOperationSupport(order = 40)
    public void logout(HttpSession session){
        //清除会话
        session.removeAttribute("user");
    }

    /**
     * 5.注册功能2:该功能无实际意义,只是为了演示HttpServletRequest的使用;
     *   请求路径: /v1/user/reg2
     *   请求方法: GET
     *   请求参数: username password email phone
     *   返回响应: 注册成功的JsonResult
     *
     *   测试: http://localhost:8080/v1/user/reg2?username=lucy&password=123456&email=lucy@163.com&phone=13111112222
     */
    @GetMapping("/reg2")
    public JsonResult reg2(HttpServletRequest request){
        //1.获取客户端传递的参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        log.debug("注册业务,参数:" + username + ", " + password + ", " + email + ", " + phone);
        //2.请求方法
        String method = request.getMethod();
        //3.获取客户端的IP地址
        String addr = request.getRemoteAddr();
        log.debug("注册业务,请求方法:" + method + ", 客户端IP:" + addr);
        //4.获取会话对象
        HttpSession session = request.getSession();

        return JsonResult.ok();
    }
}
















